package com.ljh.server.handler;

import com.ljh.message.LoginRequestMessage;
import com.ljh.message.LoginResponseMessage;
import com.ljh.server.service.UserServiceFactory;
import com.ljh.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author: Themberfue
 * @date: 2025/5/29 21:01
 * @description:
 */
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override // ? 处理客户端发送来的请求
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername(), password = msg.getPassword();
        // TODO 1. 验证用户名和密码
        boolean login = UserServiceFactory.getUserService().login(username, password);
        // TODO 2. 构造登录响应
        LoginResponseMessage loginResponseMessage;
        if (login) {
            loginResponseMessage = new LoginResponseMessage(true, "登录成功");
            SessionFactory.getSession().bind(ctx.channel(), username);
        } else {
            loginResponseMessage = new LoginResponseMessage(false, "用户名或密码错误");
        }
        // TODO 3. 向客户端发送响应
        // ! 依此经过自定义协议编解码器、日志处理器 和 LTC 处理器
        ctx.writeAndFlush(loginResponseMessage);
    }
}
